#include "../public/_public.h"
using namespace std;

CSEM sem;
struct st_pid
{
    int pid;       // 进程编号
    char name[51]; // 进程名称
};
int main(int argc, char *argv[])
{
    int shmid = shmget(0x5005, sizeof(st_pid), 0640 | IPC_CREAT);
    if (shmid == -1)
    {
        printf("shmget(0x5005) failed\n");
        return -1;
    }

    // 如果信号量已存在 获取信号量; 如果不存在 则创建它并初始化为value
    if (sem.init(0x5005) == false)
    {
        printf("sem.init(0x5005) failed\n");
        return -1;
    }

    struct st_pid *stpid;
    stpid = (struct st_pid *)shmat(shmid, 0, 0);
    if (stpid == (void *)-1)
    {
        printf("shmat(0x5005) failed\n");
        return -1;
    }

    printf("aaa time==%d,val==%d\n", time(0), sem.value());
    // 加锁
    sem.P();
    printf("bbb time==%d,val==%d\n", time(0), sem.value());
    printf("pid===%d  name==%s\n", stpid->pid, stpid->name);
    stpid->pid = getpid();
    sleep(10);
    strcpy(stpid->name, argv[1]);
    printf("pid===%d  name==%s\n", stpid->pid, stpid->name);
    printf("ccc time==%d,val==%d\n", time(0), sem.value());
    // 解锁
    sem.V();
    printf("ddd time==%d,val==%d\n", time(0), sem.value());
    shmdt(stpid);

    return 0;
}
